package conqueror.com.camerarecord;

import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import conqueror.com.camerarecord.utils.FileUtil;
import conqueror.com.camerarecord.utils.TimeUtils;


public class RecordService extends Service implements View.OnClickListener, SurfaceHolder.Callback {
    private MediaRecorder mediarecorder;// 录制视频的类
    private int recordTime;
    private SurfaceView surfaceViewFront;
    private SurfaceHolder surfaceHolderFront;
    private String TAG = "RecordService";
    private IBinder mBinder = new LocalBinder();
    //本来是不允许设成公共的
    public FrameLayout fl;
    public AboutCreateWindow mWindowUtil;
    private Button takePhoto, record, lock;
    private boolean flag = true;
    private boolean isRecording = false;
    private boolean isEmergencyRecord = false;
    private TextView recordTimeTV;
    private Camera mCameraFront;
    private AboutCamera mAboutCamera;


    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    //获取绑定的服务
    public class LocalBinder extends Binder {
        public RecordService getService() {
            return RecordService.this;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.e(TAG, "-------getMessage----***" + msg.what);
            recordTimeTV.setText(TimeUtils.secToTime(msg.what));
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        initView();
        //窗口显示
        mWindowUtil = new AboutCreateWindow(getApplicationContext());
        mWindowUtil.createFloatWindow(fl);
    }

    /**
     * 初始化View
     */
    private void initView() {
        //挂载布局
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.recordmain, null);
        //容器
        fl = (FrameLayout) view.findViewById(R.id.framebig);

        surfaceViewFront = (SurfaceView) view.findViewById(R.id.surfacefront);
        surfaceHolderFront = surfaceViewFront.getHolder();
        surfaceHolderFront.addCallback(this);

        recordTimeTV = (TextView) view.findViewById(R.id.record_time);//显示时间

        takePhoto = (Button) view.findViewById(R.id.takePhoto);//拍照
        takePhoto.setOnClickListener(this);

        record = (Button) view.findViewById(R.id.Record);//录像
        record.setOnClickListener(this);

        lock = (Button) view.findViewById(R.id.Lock);//有锁视频
        lock.setOnClickListener(this);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        surfaceHolderFront = holder;
        //初始化
        mAboutCamera = new AboutCamera(Camera.CameraInfo.CAMERA_FACING_BACK);
        mCameraFront = mAboutCamera.mCameraFront;//获取相机
        mAboutCamera.startFrontPreview(surfaceHolderFront);//开始预览
        startRecord(0);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        surfaceHolderFront = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        stopRecord();
        stopPreview();
        flag = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.takePhoto:
                takePhoto.setClickable(false);
                if (isRecording) {
                    stopRecord();
                    record.setText("录制");
                    isRecording = false;
                }
                mAboutCamera.getPreViewImage();//拍照预览
                mAboutCamera.takePhonePicture();//拍照
                takePhoto.setClickable(true);
                Log.e(TAG, "takepicture1");
                break;
            case R.id.Record:
                if (isRecording) {
                    record.setEnabled(false);
                    stopRecord();
                    record.setText("录制");
                    record.setEnabled(true);
                } else {
                    record.setEnabled(false);//解决快速按钮问题
                    startRecord(0);
                    record.setText("停止");
                    record.setEnabled(true);
                }
                break;
            case R.id.Lock:
                //TODO
                break;
        }
    }


    /**
     * 开始录影
     *
     * @param type(录制类型)
     */
    public void startRecord(int type) {
        mediarecorder = new MediaRecorder();// 创建mediarecorder对象
        if (mCameraFront != null) {
            mCameraFront.unlock();
            mediarecorder.setCamera(mCameraFront);

            mediarecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            // 设置录制文件质量，格式，分辨率之类，这个全部包括了
            mediarecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
//            mediarecorder.setOutputFormat();
//             mediarecorder.setVideoSize();
//             mediarecorder.setVideoFrameRate();
//              mediarecorder.setPreviewDisplay(surfaceHolderFront.getSurface());
            mediarecorder.setOrientationHint(90);
            mediarecorder.setOutputFile(new FileUtil().getVideoPath(type));

            try {
                mediarecorder.prepare();
                mediarecorder.start();
                flag = true;
                isRecording = true;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            /**
             * 发送显示时间
             */
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isRecording) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Log.e(TAG, e.getMessage());
                        }
                        recordTime++;
                        Log.e(TAG, "----sendMessage---------" + recordTime);
                        handler.sendEmptyMessage(recordTime);
                    }
                }
            }).start();

            /**
             * 录制时测试专用,在destroyed时候结束
             */
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (flag) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        Log.e(TAG, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    }
                }
            }).start();
        }
    }

    /**
     * 枷锁录制
     */
    public void emergencyRecordStart() {
        record.setEnabled(false);
        if (isRecording) {
            stopRecord();
            startRecord(1);
            isEmergencyRecord = true;
            record.setEnabled(true);
        } else if (!isRecording) {
            startRecord(1);
        }
    }

    /**
     * 停止录制
     */
    public void stopRecord() {
        if (mediarecorder != null) {
            mediarecorder.setOnErrorListener(null);
            mediarecorder.setOnInfoListener(null);
            mediarecorder.setPreviewDisplay(null);
            try {
                mediarecorder.stop();
            } catch (RuntimeException stopException) {
                Log.e(TAG, stopException.getMessage());
            }
            mediarecorder.reset();
            mediarecorder.release();
            isRecording = false;
            Log.e(TAG, "--------------- record stoped");
        }
    }

    /**
     * 停止预览
     */
    public void stopPreview() {
        if (mCameraFront != null) {
            mCameraFront.stopPreview();
            mCameraFront.release();
            mCameraFront = null;
            flag = false;
            Log.e(TAG, "preview stoped");
        }
    }


    @Override
    public void onDestroy() {
        Log.e(TAG, "service destory");
        stopRecord();
        stopPreview();
        surfaceHolderFront.removeCallback(this);
        mWindowUtil.removeWindow(fl);//移除窗口
        this.stopSelf();
    }
}

